package com.Utils.Tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FileTwoMd5 {

    private static final int BUFFER_SIZE = 8192; // 设置缓冲区大小为8KB

    // 将字节数组转换为十六进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            hexString.append(String.format("%02x", b));
        }
        return hexString.toString();
    }

    // 计算指定文件路径的MD5摘要
    public static String calculateMD5OfFile(String filePath) throws NoSuchAlgorithmException, IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new IOException("File does not exist: " + filePath);
        }

        try (FileInputStream fis = new FileInputStream(file)) {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead;

            while ((bytesRead = fis.read(buffer)) != -1) {
                md.update(buffer, 0, bytesRead);
            }

            return bytesToHex(md.digest());
        }
    }

    public static void main(String[] args) {
        try {
            // 指定本地文件的路径
            String filePath = "D:\\picture\\证件照片\\8d266249-f937-4392-852d-8465c4209283.jpg"; // 替换为你的文件路径

            // 计算并打印MD5摘要
            String md5 = calculateMD5OfFile(filePath);
            System.out.println("MD5摘要: " + md5);
        } catch (IOException e) {
            System.err.println("I/O error occurred: " + e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            System.err.println("Unsupported algorithm: " + e.getMessage());
        }
    }
}